<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box,
        .box2 {
            background: rgb(235, 125, 125);
            margin: 0 auto;
            width: 800px;
            height: 100px;
            display: grid;
            grid-template-columns: repeat(4, minmax(50px, 1fr));
            gap: 20px;
        }

        .box2 {
            margin: 50px auto;
        }

        div[class^="item"] {
            background: rgb(187, 235, 125);
            text-align: center;
            line-height: 100px;
            cursor: move;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="item1" draggable="true">item1</div>
        <div class="item2" draggable="true">item2</div>
        <div class="item3" draggable="true">item3</div>
        <div class="item4" draggable="true">item4</div>
    </div>
    <div class="box2"></div>
</body>

<script>
    var box = document.querySelector('.box');
    var box2 = document.querySelector('.box2');

    function moveout(element) {//拖拽源地的函数
        element.addEventListener("dragstart", function (e) {
            e.dataTransfer.setData("text/plain", e.target.className);
            // console.log()
        });
    }
    function moveend(element) {//拖拽目标地的函数
        element.addEventListener('dragover', function (e) {
            e.preventDefault();
        });
        element.addEventListener('drop', function (e) {
            e.preventDefault();
            var classname = e.dataTransfer.getData('text/plain');
            console.log(classname);
            var el = document.querySelector('.' + classname);//根据id获取元素
            this.append(el);//把元素追加到drop区.
        })
    }
    moveout(box);moveout(box2);

    
    moveend(box2);moveend(box);

    

</script>

</html>